package com.hunlian.makelove.net;

import android.content.Context;
import android.text.TextUtils;

import com.hunlian.makelove.AppApplication;
import com.hunlian.makelove.tools.LogTools;
import com.hunlian.makelove.tools.MyToast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 接口请求基类 支持缓存，缓存机制如下： 不能得到正常返回时（服务器无返回），吐司提示原因，若有缓存则返回缓存
 * 得到正常返回时，若是成功数据，则缓存本次获取的数据，否则直接吐司提示（不缓存本次得到的数据，也不返回上次的缓存数据）
 * 
 * @author jiangshunbin
 * 
 */
public class InterfaceServiceVisit extends RequestHttp {
	// 接口参数通用字段名
	public static final String PARAM_FUNCTION_ID = "functionId";
	public static final String PARAM_PARAMS = "params";
	public static final String PARAM_PARAMS_SIGN = "sign";

	private String functionId;
	// 不含sign的参数，若需要sign，则在getParamter()时添加
	// LinkedHashMap会保证参数的顺序
	protected Map<String, String> paramterData = new LinkedHashMap<String, String>();
	private StringResponseCallbackListener mCallback = null;
	private Context mContext;

	public InterfaceServiceVisit(Context context) {
		mContext = context;
		paramterData.put("time1", AppApplication.SIGNMD5);
	}

	public String getFunctionId() {
		return functionId;
	}

	public void setFunctionId(String functionId) {
		this.functionId = functionId;
	}
	
	public void setParamterData(LinkedHashMap<String, String> paramterData){
		this.paramterData = paramterData;
	}

	// 获取参数中的params部分，不包括sign，在接口继承的子类中，可按照需要的顺序自己重写此方法
	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected String getParams() {
		String params = "";

		Iterator it = paramterData.entrySet().iterator();
		while (it.hasNext()) {
			Entry<String, String> item = (Entry<String, String>) it.next();
			if (TextUtils.isEmpty(params)) {
				params = "\"" + item.getKey() + "\":\"" + item.getValue() + "\"";
			} else {
				params = params + ", " + "\"" + item.getKey() + "\":\"" + item.getValue() + "\"";
			}
		}
		return params;
	}

	// 返回接口的请求参数（json字符串形式）
	public String getParamter() {
		String sign = "";
		String params = getParams();

		if (!TextUtils.isEmpty(sign)) {
			if(TextUtils.isEmpty(params)){
				params = "\"" + PARAM_PARAMS_SIGN + "\":\"" + sign + "\"";
			}else{
				params = params + ", " + "\"" + PARAM_PARAMS_SIGN + "\":\"" + sign + "\"";
			}
		}
		
		params = "{" + params + "}";
		LogTools.e("传入参数：" + "{\"" + PARAM_FUNCTION_ID + "\":\"" + getFunctionId() + "\", \"" + PARAM_PARAMS + "\":" + params + "}");
		LogTools.e("paramter: "+getUrl(paramterData));
		return "{\"" + PARAM_FUNCTION_ID + "\":\"" + getFunctionId() + "\", \"" + PARAM_PARAMS + "\":" + params + "}";
	}

	/**
	 * post 请求
	 * @author Jiangshunbin
	 * @date 2015-11-29
	 *
	 * @param callback
	 */
	protected void doPost(StringResponseCallbackListener callback) {
		doPost(getParamter(), callback);
	}

	protected void doPost(String paramter, StringResponseCallbackListener callback) {
		if (!AppApplication.networkAvailable) {
			MyToast.showShort("没有网络");
			return;
		}
		doPost(ServiceInterfaceDef.SERVICE_URL, paramter, callback);
	}

	protected void doPost(String url, final String paramter, StringResponseCallbackListener callback) {
		mCallback = callback;

		JSONObject json;
		try {
			json = new JSONObject(paramter);
			LogTools.e("url: "+url);
			//LogTools.e("paramter: "+paramter);
			/**
			postVisit(mContext, url, json, new StringResponseCallbackListener() {
				@Override
				public void onSuccess(String data) {
					LogTools.e("返回成功: "+data);
					if(TextUtils.isEmpty(data)){
						//Toast.makeText(mContext,"无数据",Toast.LENGTH_SHORT).show();
						if (mCallback != null) {
							mCallback.onFailure("-1", "返回数据为空",null);
						}
						return;
					}
					try {
						JSONObject obj = new JSONObject(data);
						String message = obj.getString("message");
						String status = obj.getString("status");
						
						if (ServiceInterfaceDef.SERVICE_RETURN_SUCCESSFUL.equals(status)) {
							if (mCallback != null) {
								String beans = obj.getString("beans");
								mCallback.onSuccess(beans);
							}
						}else if(ServiceInterfaceDef.SERVICE_RETURN_FAIL.equals(status)){
							if (mCallback != null) {
								String beans = obj.getString("beans");
								if(!TextUtils.isEmpty(beans)){
									mCallback.onFailure(status, message,beans);
								}else{
									mCallback.onFailure(status, message,null);
								}

							}
						} else {
							//LogTools.e("请求异常:" + status + "(" + message + ")，参数：" + paramter);
							if (mCallback != null) {
								mCallback.onFailure(status, data,null);
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
						if (mCallback != null) {
							mCallback.onFailure("exception", e.getMessage(),null);
						}
					}
				}
				
				@Override
				public void onFailure(String errCode, String errMessage,String errData) {
					if (mCallback != null) {
						mCallback.onFailure(errCode, errMessage,null);
					}
				}

			});
			 */

			postVisit(mContext, url, json).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
				@Override
				public void onCompleted() {
				}

				@Override
				public void onError(Throwable e) {
					if (mCallback != null) {
						mCallback.onFailure("",e.getMessage(),null);
					}
				}

				@Override
				public void onNext(String data) {
					LogTools.e("返回成功: "+data);
					if(TextUtils.isEmpty(data)){
						//Toast.makeText(mContext,"无数据",Toast.LENGTH_SHORT).show();
						if (mCallback != null) {
							mCallback.onFailure("","返回数据为空",null);
						}
						return;
					}
					try {
						JSONObject obj = new JSONObject(data);
						String message = obj.getString("message");
						String status = obj.getString("status");

						if (ServiceInterfaceDef.SERVICE_RETURN_SUCCESSFUL.equals(status)) {
							if (mCallback != null) {
								String beans = obj.getString("beans");
								mCallback.onSuccess(beans);
							}
						}else if(ServiceInterfaceDef.SERVICE_RETURN_FAIL.equals(status)){
							if (mCallback != null) {
								String beans = obj.getString("beans");
								if(!TextUtils.isEmpty(beans)){
									mCallback.onFailure(status, message,beans);
								}else{
									mCallback.onFailure(status, message,null);
								}

							}
						} else {
							//LogTools.e("请求异常:" + status + "(" + message + ")，参数：" + paramter);
							if (mCallback != null) {
								mCallback.onFailure(status, data,null);
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
						if (mCallback != null) {
							mCallback.onFailure("exception", e.getMessage(),null);
						}
					}
				}
			});

		} catch (JSONException e) {
			e.printStackTrace();
			
			if(mCallback != null){
				mCallback.onFailure("",e.getMessage(),null);
			}
		}
		
	}


	public static String getUrl(Map<String,String> params){
		int index = 0;
		StringBuffer sb = new StringBuffer();
		Set<String> keys = params.keySet();
		Iterator<String> iterator = keys.iterator();
		while(iterator.hasNext()){
			String key = iterator.next();
			String value = params.get(key);
			if(index==0){
				sb.append("?").append(key).append("=").append(value);
			}else{
				sb.append("&").append(key).append("=").append(value);
			}
			index++;
		}
		return sb.toString();
	}

}
